<?php

namespace App\Models\Logic;

use App\Exceptions\ApiException;
use App\Models\OrderLog;
use Illuminate\Support\Facades\DB;

use Illuminate\Database\Eloquent\Model;
use App\Api\Controllers\PayController;
use function PHPSTORM_META\type;

class Wallet extends Model
{

    public $user_id = 0;		// 平台唯一用户ID
    public $order_no = '';		// 唯一订单号
    public $product_name = '';	// 订单商品/主题名
    public $return_url = '';	// 同步回调地址，可带参数
    public $notify_url = '';	// 异步回调地址
    public $pay_type = '';		// 支付方式，内部支付为 wallet 否则是第三方的名字
    public $pay_type_group = '';// 组合支付json

    static function wallet($uid,$purse = null){
        $param = [
            ['uid','=',$uid],
            ['status', '=', 1]
        ];
        $data = DB::table('fund_user_purse')->select('pursetypeid','balance','balancefreeze')->where($param)->get();
        $result = [];
        foreach($data as $k => $v){
            if($v->pursetypeid == 3){
                $wallet_name = 'wallet_vcoin';
            }else{
                $wallet_name = 'wallet_none'; //待定
            }
            $result[$wallet_name]['pursetypeid'] = $v->pursetypeid;
            $result[$wallet_name]['balance'] = $v->balance / 100;
            $result[$wallet_name]['balancefreeze'] =abs($v->balancefreeze) / 100;
            $result[$wallet_name]['available'] = round($result[$wallet_name]['balance'] - abs($result[$wallet_name]['balancefreeze']),2);
        }
        unset($data);
        if($purse){
            return $result[$purse];
        }
        return $result;

    }

    /**
     * @return mixed
     * 统一下单
     */
    public function unified(){
        $user_id = $this->user_id;
        $order_no = $this->order_no;
        $product_name = $this->product_name;
        $return_url = $this->return_url;
        $notify_url = $this->notify_url;
        $card_account = $this->card_account;
        $mobile = $this->mobile;
        $account_card_id = $this->account_card_id;
        $card_no = $this->card_no;
        $pay_type = $this->pay_type;
        $pay_type_group = htmlspecialchars_decode($this->pay_type_group);

        $pay_type_group_array = json_decode($pay_type_group,true);
        $pay_type_three = '';
        $amount = 0;
        foreach($pay_type_group_array as $pay_type2 => $amount_unit){
            if($wallet_pos = strpos($pay_type2,'wallet_') === 0){
                // V币支付金额
                if(substr($pay_type2,7) == 'vcoin'){
                    $amount+= $amount_unit;
                }
            }else{
                $pay_type_three = $pay_type2;
            }
            $amount = $amount_unit;
        }
        if($pay_type_three){
            $pay_type = $pay_type_three;
        }else{
            $pay_type = 'wallet';
        }

        $method = $pay_type.'Pay';
        $param = compact('user_id','user_name','order_no','product_name','return_url','notify_url','card_account','mobile','account_card_id','card_no','pay_type','pay_type_group','merchant_no','wechat_appid','wechat_openid');
        $data = $this->$method($param);
        return $data;
    }


    /**
     * @param $param
     * @return array
     * 钱包支付
     */
    private function walletPay($param){
        $order_log = new OrderLog();
        $data['status'] = 0;
        $error_msg = '';
        //添加fund_transfer记录
        $order = DB::table('user_level_order')->where('order_no',$this->order_no)->first();
        if($order){
            $outamount = $order->money * 100;
            DB::beginTransaction();
            try{
            $flag = $this->transfer($this->order_no,10004,$this->user_id,3,3,$outamount,
                    1,2,3,$outamount);

            //修改订单状态
            $pay_time = date('Y-m-d H:i:s');
            $order_flag = DB::table('user_level_order')->where('order_no',$this->order_no)->update(['status'=>1,'pay_time'=>$pay_time]);
            //修改用户会员信息
                $order_info = DB::table('user_level_order')->where('order_no',$this->order_no)->first();
                $now_level = $order_info->now_level;
                $level_info = explode('-',$now_level);
                $isstockholder = $level_info[0];
                $vip_level = $level_info[1];

                //查询订单中会员日期
                $vip_level_info = DB::table('user_level_rule')->where([['isstockholder','=',$isstockholder],['vip_level','=',$vip_level]])->first();
                $vip_indate = $vip_level_info->indate;

                //获取用户之前会员到期日期
                $user_vip_indate = get_user_info_by_id($this->user_id)->vip_indate;

                if(empty($user_vip_indate)){
                    $user_vip_indate = date('Y-m-d H:i:s',strtotime("+$vip_indate day"));
                }else{
                    $user_vip_indate = date('Y-m-d H:i:s',strtotime("+$vip_indate day",strtotime($user_vip_indate)));
                }
                $user_data = [
                    'isstockholder' =>  $isstockholder,
                    'vip_level'     =>  $vip_level,
                    'vip_indate'    =>  $user_vip_indate,
                    'updated_at'    =>  time2date(),
                ];
                $user_flag = DB::table('users')->where('id',$this->user_id)->update($user_data);
            }catch(Exception $e){
                $error_msg = $e->getMessage();
            }
            $error_msg = $error_msg ?: '';
            if($flag && $order_flag &&$user_flag){
                DB::commit();
                $data['status'] = 1;
                $data['pay_time'] = $pay_time;
                $order_log->addRecord($this->user_id,$this->order_no,'订单支付成功',$error_msg);
                //$flag_log = $this->log($product_name,$reason,1,$detail);
            }else{
                DB::rollBack();
                $order_log->addRecord($this->user_id,$this->order_no.'订单支付失败',$error_msg);
                //$flag_log = $this->log($product_name,$reason,1,$detail);
            }
        }
        return $data;
    }

    private function transfer($detail,$reasoncode,$outuserid,$outusertypeid,$outpursetypeid,$outamount,$intouserid,$intousertypeid,$intopursetypeid,$intoamount){

        $out_where = [
            ['uid','=',$outuserid],
            ['pursetypeid','=',$outpursetypeid],
            ['status','=',1],
        ];
        $in_where = [
            ['uid','=',$intouserid],
            ['pursetypeid','=',$intopursetypeid],
            ['status','=',1],
        ];
        $out_purse_info = DB::table('fund_user_purse')->where($out_where)->first();
        $in_purse_info = DB::table('fund_user_purse')->where($in_where)->first();
        $out_purse_balance = strval($out_purse_info->balance - $outamount);
        $in_purse_balance = strval($in_purse_info->balance + $intoamount);
        if($out_purse_balance < 0){
            return false;
        }
        $result1 = DB::table('fund_user_purse')->where('id',$out_purse_info->id)->update(['balance'=>$out_purse_balance,'updated_at'=>date('Y-m-d H:i:s')]);
        $result2 = DB::table('fund_user_purse')->where('id',$in_purse_info->id)->update(['balance'=>$in_purse_balance,'updated_at'=>date('Y-m-d H:i:s')]);
        $data = [
            'reasoncode'    =>  $reasoncode,
            'outuserid'     =>  $outuserid,
            'outusertypeid' =>  $outusertypeid,
            'outpursetypeid'=>  $outpursetypeid,
            'outpurseid'    =>  $out_purse_info->id,
            'outamount'     =>  $outamount,
            'outbalance'    =>  $out_purse_balance,
            'intouserid'    =>  $intouserid,
            'intousertypeid'=>  $intousertypeid,
            'intopursetypeid'=> $intopursetypeid,
            'intopurseid'   =>  $in_purse_info->id,
            'intoamount'    =>  $intoamount,
            'intobalance'   =>  $in_purse_balance,
            'detail'        =>  $detail,
            'status'        =>  1,
            'created_at'    =>  date('Y-m-d H:i:s'),
            'updated_at'    =>  date('Y-m-d H:i:s'),
        ];
        $id = DB::table('fund_transfer')->insertGetId($data);
        if($result1 && $result2 && $id){
            return true;
        }else{
            return false;
        }
    }
}
